import router from '@/router'
import store from '@/store'
import { setTimeout } from 'core-js'
import NProgress from 'nprogress' // 引入一份进度条插件
import 'nprogress/nprogress.css' // 引入进度条样式
// import { asyncRoutes } from '@/router'

// 路由前置守卫
const whiteList = ['/login', '404']
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  const token = store.getters.token
  if (token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      if (!store.state.user.UserInfo.userId) {
        // 得到UserInfo里权限用于渲染页面
        const res = await store.dispatch('user/setUserInfo')
        // 调用该方法并传值用于接收过滤后的路由信息
        const otherRoutes = await store.dispatch('permission/filterRoutes', res.roles.menus)
        // 这里一定要把404放在路由规则的最后面,防止刷新页面报错404
        router.addRoutes([...otherRoutes, { path: '*', redirect: '/404', hidden: true }])
        next({ // router.addRoutes(asyncRoutes) 是异步的 需要重进一次
          ...to,
          replace: true
        })
      }
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach((to, from) => {
  setTimeout(function() {
    NProgress.done()
  }, 1000)
})
